package com.bs.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.bs.bean.ResultInfo;
import com.bs.bean.User;
import com.bs.service.UserService;
import com.bs.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${pic.path}")
    private String filePath;


    //用户登录
    @PostMapping("/login")
    public String login(String username, String password, HttpServletRequest request,ModelMap model) {

        password= MD5Utils.md5(password);
        User user = userService.login(username,password);

        if(user!=null){
            //登陆成功
            request.getSession().setAttribute("user",user);
            return "forward:/getAllNews";
        }else{
            //登陆失败
//            request.getSession().setAttribute("errorLogin","用户名或密码失败！");
            model.addAttribute("errorLogin","用户名或密码失败！");
            return "login";
        }


    }

    @GetMapping("/isLogin")
    @ResponseBody
    public ResultInfo checkJsessionid(HttpSession session) {

        User user = (User) session.getAttribute("user");

        //检验是否存在user值来判断是否以及登录
        if (user != null) {

            //将已登录的用户的头像和用户名返回
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userPicture", user.getPicture());
            resultMap.put("username", user.getUsername());
            return ResultInfo.successInfo("已登录！", resultMap);

        } else {
            return ResultInfo.failInfo("请先登录！");
        }

    }


    //用户注册
    @PostMapping(value = "/register")
    public String register(User user,ModelMap model) {
        User user1 = userService.getUserByUserName(user.getUsername());
        if(user1==null){
            String password = MD5Utils.md5(user.getPassword());
            user.setPassword(password);
            userService.save(user);
            model.addAttribute("success","注册成功,请登录！");
            return "login";
        }else{
            model.addAttribute("errorRegister","名称不能重复");
            return "register";
        }

    }


    //用户退出
    @GetMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "forward:/getAllNews";
    }


    //修改用户
    @RequestMapping(value = "/updateUser")
    public String updateUser(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password,
                             @RequestParam(value = "email") String email, ModelMap model, HttpSession session) {
        User user = (User)session.getAttribute("user");
        String username2 = user.getUsername();
        if(user!=null) {
            String md5Pwd = MD5Utils.md5(password);
//            user.setPassword(md5Pwd);
//            userService.save(user);
            userService.updatePasswordByUserName(md5Pwd,email,username2,username);
            model.addAttribute("updateSuccess","修改成功，请重新登录！");
        }
        return "redirect:/toLogin";
    }

    @PostMapping("/uploadPic")
    public String up(@RequestBody MultipartFile file, HttpSession session) throws Exception{

        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if(extName.equals(".jpg") || extName.equals(".gif") || extName.equals(".png")){
            String fileName = UUID.randomUUID().toString()+extName;
            String lastName = "/image/"+fileName;
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(filePath+fileName)));
            User user = (User) session.getAttribute("user");
            userService.updatePicture(user.getUsername(), "/image/"+fileName);
            user.setPicture(lastName);

            return "redirect:/toUserHome";
        }else{
            return "failed";
        }

    }

    //获取积分排行榜
    @GetMapping(value = "/getScoreBoardList")
    public String getScoreBoardList(HttpServletRequest request,
                                    @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum, ModelMap model) {

        PageHelper.startPage(pageNum,5);
        List<User> list =userService.getScoreBoardList();
        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("topicLists",pageInfo);
        return "frontPage/scoreboardList";
    }

    @GetMapping("/searchUser/{searchInfo}")
    @ResponseBody
    public ResultInfo searchUser(@PathVariable String searchInfo){

        User searchUsersData2 = userService.searchUsersByKeyword(searchInfo);
        if(searchUsersData2 != null) {
            return ResultInfo.successInfo("查询成功！", searchUsersData2);
        } else{
            return ResultInfo.failInfo("查询失败！");
        }
    }

}
